<?php
namespace Robot\Controller;
use Common\Controller\RobotController;
use Think\Cache\Driver\Redis;
class PlatformController extends RobotController {

    const APPID = 'wxff511737a867ae35';
    const AppSecret = 'f45525f46e400021f3fbdf1d6eab998f';
    const Token = 'yuanyi2018';
    const Key = 'dH0HWACjxmul871USoBbHRC2qi01bEgWKJVJizLxT12';

    public function ticket(){

        if (!isset($_GET['echostr'])) {
            $this->gettick();
        }else{
            $this->valid();
        }
    }

   //获取tick
    private function gettick(){

        include_once "WXBizMsgCrypt.php";

        $encodingAesKey = 'dH0HWACjxmul871USoBbHRC2qi01bEgWKJVJizLxT12';
        $token = self::Token;
        $appId = self::APPID;

        $timeStamp  = empty($_GET['timestamp'])     ? ""    : trim($_GET['timestamp']) ;

        $nonce      = empty($_GET['nonce'])         ? ""    : trim($_GET['nonce']) ;

        $msg_sign   = empty($_GET['msg_signature']) ? ""    : trim($_GET['msg_signature']);

        // 接受POST 传过来的数据

        $encryptMsg = file_get_contents("php://input");


        $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);

        $xml_tree = new \DOMDocument();

        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;

        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);

        $msg = '';

        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        $this->logResult('log.log','$errCode：'.$errCode."\n\r");
        if ($errCode == 0)
        {

            $xml = new \DOMDocument();

            $xml->loadXML($msg);
            $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');

            $component_verify_ticket = $array_e->item(0)->nodeValue;

            $redis = new Redis();

            $redis->set('ticket',$component_verify_ticket,3600);

            echo 'success';

        } else

        {

            $this->logResult('log.log','解密后失败：'.$errCode."\n");
            echo 'success';
        }

    }


    // 日志

    private function logResult($path,$data)

    {

        header("content-type:text/html;charset=utf-8");

        file_put_contents($path, '['.date('Y-m-d : h:i:sa',time()).']'.$data."\n\r",FILE_APPEND);

    }


    //验证签名
    private function valid()
    {

        $echoStr = $_GET["echostr"];

        $signature = $_GET["signature"];

        $timestamp = $_GET["timestamp"];

        $nonce = $_GET["nonce"];

        $tmpArr = array(self::Token, $timestamp, $nonce);

        sort($tmpArr);

        $tmpStr = implode($tmpArr);

        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature)

        {
            echo $echoStr;

            exit;

        }

    }


    /**
     * 平台发布验证
     */
    public function verify()
    {

        include_once "WXBizMsgCrypt.php";
//encodingAesKey和token均为申请三方平台是所填写的内容
        $encodingAesKey = self::Key;
        $token = self::Token;
        $appId = self::APPID;

        $timeStamp = empty($_GET['timestamp']) ? "" : trim($_GET['timestamp']);

        $nonce = empty($_GET['nonce']) ? "" : trim($_GET['nonce']);

        $msg_sign = empty($_GET['msg_signature']) ? "" : trim($_GET['msg_signature']);

        $app_id = $_GET['appid'];

        $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
        //获取到微信推送过来post数据（xml格式）
        $postArr = file_get_contents("php://input");

        $msg = '';

        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $postArr, $msg);

        $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);

        //第三方平台全网发布检测返回api文本消息测试
        if (strpos($postObj->Content, 'QUERY_AUTH_CODE') !== false) {
            $query_auth_code = str_replace('QUERY_AUTH_CODE:', '', $postObj->Content);
            $info = $this->getAuthInfo($query_auth_code);

            $access_info = $info['authorization_info']['authorizer_access_token'];
            $param = array();
            $param['touser'] = "$postObj->FromUserName";
            $param['msgtype'] = 'text';
            $param['text']['content'] = $query_auth_code . '_from_api';

            $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_info;
            $test = $this->post_data($url, json_encode($param));
            echo $test;
        }
    }

    private function post_data($url,$postdata){

        $ch = curl_init(); //用curl发送数据给api
        // curl_setopt( $ch, CURLOPT_POST, true );
        curl_setopt( $ch, CURLOPT_POST, true );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postdata );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        $response = curl_exec($ch);
        curl_close( $ch );
        $rest = json_decode($response,true);
        return $rest;
    }

   private function getAuthInfo($query_auth_code){

       $redis = new Redis();

       $access_token = $redis->get('component_access_token');

        $urlAuth = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=$access_token";
        $postdata = array(
            'component_appid' =>self::APPID,
            'authorization_code' =>$query_auth_code,
        );
        $postdata = json_encode($postdata);

        $resultAuth =$this->post_data($urlAuth,$postdata);
        return $resultAuth;

    }
}